//
//  ComposeTypeView.swift
//  Practice
//
//  Created by miaozhihui on 2017/3/8.
//  Copyright © 2017年 DeKuTree. All rights reserved.
//

import UIKit
import pop

/// 撰写微博类型视图
class ComposeTypeView: UIView {
    
    @IBOutlet weak var scrollView: UIScrollView!
    /// 关闭按钮 X 约束
    @IBOutlet weak var closeCons: NSLayoutConstraint!
    /// 返回按钮
    @IBOutlet weak var backButton: UIButton!
    /// 返回按钮 X 约束
    @IBOutlet weak var backCons: NSLayoutConstraint!
    /// 完成回调
    private var completionBlock: ((_ clsName: String?)->())?
    
    fileprivate let buttonsInfo = [["imageName":"tabbar_compose_idea","title":"文字","clsName":"ComposeController"],
                               ["imageName":"tabbar_compose_photo","title":"照片/视频"],
                               ["imageName":"tabbar_compose_weibo","title":"长微博"],
                               ["imageName":"tabbar_compose_lbs","title":"签到"],
                               ["imageName":"tabbar_compose_review","title":"点评"],
                               ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                               ["imageName":"tabbar_compose_friend","title":"好友圈"],
                               ["imageName":"tabbar_compose_wbcamera","title":"微博相机"],
                               ["imageName":"tabbar_compose_music","title":"音乐"],
                               ["imageName":"tabbar_compose_shooting","title":"拍摄"],
                               ]
    class func composeTypeView() -> ComposeTypeView {
        let nib = UINib(nibName: "ComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! ComposeTypeView
        // XIB 加载，默认是 600*600
        v.frame = UIScreen.main.bounds
        v.setupUI()
        return v
    }

    /// 显示视图
    func show(completion: @escaping (_ clsName: String?)->()) {
        
        // 记录闭包
        completionBlock = completion
        // 将当前视图添加到 根视图控制器的 view
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        vc.view.addSubview(self)
        
        // 开始动画
        showCurrentView()
    }
    
    /// 按钮监听方法
    ///
    /// - Parameter btn: 点击按钮
    @objc fileprivate func clickButton(selectedButton: ComposeTypeButton) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        // 选中按钮变大，未选中按钮缩小
        for (i,btn) in v.subviews.enumerated() {
            
            // 缩放动画
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (selectedButton == btn) ? 2 : 0.5
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.duration = 0.5
            btn.pop_add(scaleAnim, forKey: nil)
            
            // 渐变动画
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            
            // 添加动画监听
            if i == 0 {
                alphaAnim.completionBlock = { (_,_) in
                    // 执行回调
                    print("完成回调，展现控制器")
                    self.completionBlock?(selectedButton.clsName)
                }
            }
        }
    }
    
    /// 点击更多按钮
    @objc fileprivate func clickMore() {
        
        // scrollView 滚动到第二页
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)
        
        // 底部添加返回按钮
        backButton.isHidden = false
        let margin = scrollView.bounds.width / 6
        closeCons.constant += margin
        backCons.constant -= margin
        UIView.animate(withDuration: 0.25) {
            self.layoutIfNeeded()
        }
    }
    
    /// 返回按钮点击事件
    ///
    /// - Parameter sender: 点击按钮
    @IBAction func back(_ sender: UIButton) {
        
        // 滚动 scrollView 到第一页
        scrollView.setContentOffset(CGPoint.zero, animated: true)
        
        // 底部隐藏返回按钮
        closeCons.constant = 0
        backCons.constant = 0
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }) { (_) in
            self.backButton.alpha = 1
           self.backButton.isHidden = true
        }
    }
    /// 关闭视图
    ///
    /// - Parameter sender: 点击按钮
    @IBAction func close(_ sender: UIButton) {
        hideButtons()
    }

    
}

// MARK: - 动画
fileprivate extension ComposeTypeView {
    
    /// 弹力隐藏所有按钮
    func hideButtons() {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        for (i,btn) in v.subviews.enumerated() {
            // 创建动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            // 设置动画属性
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 400
            anim.springBounciness = 8
            anim.springSpeed = 8
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            // 添加动画
            btn.pop_add(anim, forKey: nil)
            
            if i == 0 {
                anim.completionBlock = {(_,_) -> () in
                    self.hideCurrentView()
                }
            }
        }
    }
    
    /// 渐隐自身
    func hideCurrentView() {
        // 创建动画
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        // 设置动画属性
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        // 添加到视图
        pop_add(anim, forKey: nil)
        anim.completionBlock = { (_,_) in
            self.removeFromSuperview()
        }
    }
    /// 渐显自身
    func showCurrentView() {
        
        // 创建动画
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        // 设置动画属性
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        // 添加到视图
        pop_add(anim, forKey: nil)
        
        // 添加按钮动画
        showButtons()
    }
    
    /// 弹力显示所有按钮
    func showButtons() {
        
        let v = scrollView.subviews[0]
        
        for (i,btn) in v.subviews.enumerated() {
            
            // 创建动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            // 设置动画属性
            anim.fromValue = btn.center.y + 400
            anim.toValue = btn.center.y
            // 弹力系数[0-20],值越大弹的幅度越大，默认4
            anim.springBounciness = 8
            // 弹力速度[0-20],值越大弹的越快，默认12
            anim.springSpeed = 8
            // 设置动画启动时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            // 添加动画
            btn.pop_add(anim, forKey: nil)
        }
    }
}

// MARK: - 设置UI
fileprivate extension ComposeTypeView {
    
    func setupUI() {
        
        // 为了获取正确的 scrollView 的size，必须调用下边方法
        layoutIfNeeded()
        // 设置初始rect
        let rect = scrollView.bounds
        
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0))
            
            // 向视图中添加按钮
            addButtons(v: v, idx: i * 6)
            
            // 将视图添加到 scrollView
            scrollView.addSubview(v)
        }
        
        scrollView.contentSize = CGSize(width: 2 * rect.width, height: 0)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
        
    }
    
    /// 向 v 中添加按钮
    ///
    /// - Parameters:
    ///   - v: 要添加按钮的视图
    ///   - idx: 添加按钮的起始索引
    func addButtons(v: UIView, idx: Int) {
        
        let count = 6
        
        // 创建按钮
        for i in idx..<(idx+count) {
            
            if i >= buttonsInfo.count {
                break
            }
            
            let dict = buttonsInfo[i]
            
            guard let imageName = dict["imageName"],let title = dict["title"] else {
                continue
            }
            
            // 创建按钮
            let btn = ComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            // 添加到视图
            v.addSubview(btn)
            
            // 添加监听方法
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            btn.clsName = dict["clsName"]
        }
        
        // 设置位置
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4
        for (i,btn) in v.subviews.enumerated() {
            let col = i % 3
            let row = i / 3
            let x = margin + CGFloat(col) * (margin + btnSize.width)
            let y = (row == 1) ? (v.bounds.height - btnSize.height) : 0
            btn.frame = CGRect(x: x , y: y, width: btnSize.width, height: btnSize.height)
        }
    }
    
}
